package cn.xiongxf.mq.consumer;

import cn.xiongxf.dto.PayResult2MQDTO;
import cn.xiongxf.service.ICourseUserLearnService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * MQ事务消息【支付结果】消费者 - 课程服务
 */
@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "service-course-consumer-payresult",
        topic = "topic-payresult",
        selectorExpression = "tags-payresult",
        messageModel = MessageModel.BROADCASTING  // 广播模式消费
)
public class PayResultForCourseConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private ICourseUserLearnService courseUserLearnService;

    @Override
    public void onMessage(MessageExt message) {
        if(message.getBody() == null || message.getBody().length == 0) return;
        // 解析结果对象
        PayResult2MQDTO dto = JSON.parseObject(new String(message.getBody(), StandardCharsets.UTF_8), PayResult2MQDTO.class);
        if (dto.isSuccess()) courseUserLearnService.payResultHandler(dto);
        log.info("支付结果处理：{}", dto);
    }
}
